package com.uxsino.commons.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 时间计算工具类
 */
public class TimeUtils {

    private static final Logger logger = LoggerFactory.getLogger(TimeUtils.class);

    /**
     * 计算时间与天数的加减(days为正数则进行相加，为负数则进行相减)
     * 
     * @param date
     * @param days
     * @return Date
     */
    public static Date calTime(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, +days);
        return cal.getTime();
    }

    /**
     * 将时间格式化为"HH:mm:ss"的字符串
     * 
     * @param date
     * @return
     */
    public static String formatTimeHour(Date date) {
        SimpleDateFormat timeSdf = new SimpleDateFormat("HH:mm:ss");
        return timeSdf.format(date);
    }

    /**
     * 将时间格式化为"yyyy-MM-dd HH:mm:ss"的字符串
     * 
     * @param date
     * @return String
     */
    public static String formatTime(Date date) {
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return longSdf.format(date);
    }

    /**
    * 将时间格式化为"yyyy-MM-dd"的字符串
    * 
    * @param date
    * @return String
    */
    public static String formatShortTime(Date date) {
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        return shortSdf.format(date);
    }

    /**
     * 将时间格式化为"yyyy-MM-dd HH-mm-ss"的字符串,符合文件名格式
     * 
     * @param date
     * @return String
     */
    public static String formatLongTime(Date date) {
        SimpleDateFormat longTimeSdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss-SSS");
        return longTimeSdf.format(date);
    }

    /**
     * 获取当前时间
     * 
     * @param date
     * @return Date
     */
    public static Date toDayTime() {
        return new Date();
    }

    /**
     * String类型转Date类型
     * 
     * @param dateString
     *            字符串类型的时间
     * @param format
     *            转换格式
     * @return Date
     */
    public static Date stringToDate(String dateString, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sdf.parse(dateString);
        } catch (Exception e) {
            logger.error("parse date error! dateString: " + dateString + ", format: " + format);
        }
        return date;
    }

    /**
     * 当前季度的开始时间，即2012-01-1 00:00:00
     * 
     * @return
     */
    public static Date getCurrentQuarterStartTime() {

        Calendar c = Calendar.getInstance();

        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {

        }
        return now;
    }

    public static Calendar getCalendar(String time) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = longSdf.parse(time);
            calendar.setTime(date);
        } catch (ParseException e) {

        }
        return calendar;
    }

    public static boolean between(Date beginDate, Date endDate) {
        Date now = new Date();
        return between(now, beginDate, endDate);
    }

    public static boolean between(String beginTime, String endTime, String format) {
        Date beginDate = stringToDate(beginTime, format);
        System.out.println(formatTime(beginDate));
        Date endDate = stringToDate(endTime, format);
        return between(beginDate, endDate);
    }

    public static boolean betweenInOneDay(String beginTime, String endTime) {
        String timeFormat = "HH:mm:ss";
        Date beginDate = stringToDate(beginTime, timeFormat);
        Date endDate = stringToDate(endTime, timeFormat);
        String nowDate = formatTimeHour(toDayTime());
        Date now = stringToDate(nowDate, timeFormat);
        return between(now, beginDate, endDate);
    }

    public static boolean between(Date now, Date beginDate, Date endDate) {
        return now.before(endDate) && now.after(beginDate);
    }

    /**
     * 将长整型数字转换为日期格式的字符串
     * 
     * @param time
     * @param format
     * @return
     */
    public static String convert2String(long time, String format) {
        if (time >= 0) {
            SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(time);
            if (org.apache.commons.lang3.StringUtils.isBlank(format)) {
                return longSdf.format(date);
            }
            SimpleDateFormat sf = new SimpleDateFormat(format);
            return sf.format(date);
        }
        return "";
    }

    /**
     * 将长整型数字转换为日期格式的字符串
     * 
     * @param time
     * @param format
     * @return
     */
    public static String convert2String(long time) {
        if (time >= 0) {
            SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(time);
            return longSdf.format(date);
        }
        return "";
    }

    /**
     * 日期转换
     * @param dateString 日期字符串
     * @param sdf 转换格式
     * @return
     */
    public static Date parseDate(String dateString, SimpleDateFormat sdf) {
        Date date = null;
        try {
            date = sdf.parse(dateString);
        } catch (Exception e) {
            logger.error("parse " + dateString + " to date error!", e);
        }
        return date;
    }

    /**
     *  毫秒转转成时间字符串-例如 单位为毫秒时，2分30秒3毫秒
     * @param millis 毫秒 包含 "天", "时", "分", "秒", "毫秒"
     * @param unit 单位
     * @return
     */
    public static String millis2TimeStr(Long millis, String unit) {
        String timeStr = "";
        List<String> arr = Arrays.asList("天", "时", "分", "秒", "毫秒");
        int[] gap = { 24, 60, 60, 1000 };
        String[] time = { null, null, null, null, null };
        int index = arr.indexOf(unit);
        if (millis == 0) {
            timeStr = millis + unit;
        } else {
            for (int i = index; i >= 0; i--) {
                if (millis <= 0) {
                    break;
                }
                if (i == 0) {
                    time[0] = millis + arr.get(i);
                    break;
                }
                time[i] = millis % gap[i - 1] + arr.get(i);
                millis = (long) Math.floor(millis / gap[i - 1]);
            }
            for (String str : time) {
                if (str == null) {
                    continue;
                }
                timeStr += str;
            }
        }
        return timeStr;
    }

    /**
     * 获取当天某个时刻
     * @param hourOfDay 时
     * @param minute 分
     * @param second 秒
     * @return
     */
    public static Date getCurDayTime(int hourOfDay, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
            hourOfDay, minute, second);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取某个日期的小时
     * @param date 日期
     * @return
     */
    public static Date getHourDate(Date date) {
        SimpleDateFormat longHourSdf = new SimpleDateFormat("yyyy-MM-dd HH");
        Date hourDate = null;
        try {
            hourDate = longHourSdf.parse(longHourSdf.format(date));
        } catch (Exception e) {
            logger.error("parse date error -> " + (date == null ? null : date.getTime()), e);
        }
        return hourDate;
    }

    /**
     * 获取某个日期的分钟
     * @param date 日期
     * @return
     */
    public static Date getMinDate(Date date) {
        SimpleDateFormat longMinSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date hourDate = null;
        try {
            hourDate = longMinSdf.parse(longMinSdf.format(date));
        } catch (Exception e) {
            logger.error("parse date error -> " + (date == null ? null : date.getTime()), e);
        }
        return hourDate;
    }

    /**
     * 日期转换
     * @param date 日期
     * @param format 转换格式
     * @return
     */
    public static String format(Date date, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

}
